<template>
    <div class="app-container">
        <div class="top-total">
          <div class="item">
              <h3>总消耗</h3>
              <p>{{tableData.totalCost?tableData.totalCost:0}}</p>
          </div>
          <div class="item">
              <h3>总现金消耗</h3>
              <p>{{tableData.totalRealCost?tableData.totalRealCost:0}}</p>
          </div>
          <div class="item">
              <h3>归因回收</h3>
              <p>{{tableData.monitorIncome?tableData.monitorIncome:0}}&nbsp;&nbsp;ROI({{tableData.totalCost?(tableData.monitorIncome/tableData.totalCost*100).toFixed(2):0}}%)</p>
          </div>
          <div class="item" v-if="queryParams.type==2">
              <h3>总回收</h3>
              <p>{{tableData.totalIncome?tableData.totalIncome:0}}&nbsp;&nbsp;ROI({{tableData.totalRealCost?(tableData.totalIncome/tableData.totalRealCost*100).toFixed(2):0}}%)</p>
          </div>
          <div class="item" v-if="queryParams.type==2">
              <h3>利润</h3>
              <p>{{tableData.totalIncome?(tableData.totalIncome-tableData.totalRealCost).toFixed(2):0}}</p>
          </div>
          <div class="item" v-if="queryParams.type==3 ||queryParams.type==4 ||queryParams.type==5 ||queryParams.type==6">
              <h3>利润</h3>
              <p>{{tableData.monitorIncome?(tableData.monitorIncome-tableData.totalRealCost).toFixed(2):0}}</p>
          </div>
        </div>
        <el-form :model="queryParams" ref="queryForm" v-show="showSearch" size="mini">
            <el-query-row :label="'维度'" :labelWidth="80" class="table-button-group">
                <el-col :span="8">
                    <el-button-group :autofocus="true">
                        <el-button size="mini" v-for="(item, index) in dataDimensionList" :key="item + index"
                            :disabled="item.disable" :class="[item.value === queryParams.type ? 'active' : '']"
                            @click="_changeParams('type', item.value)">
                            {{ item.name }}
                        </el-button>
                    </el-button-group>
                </el-col>
                <el-col :span="16">
                    <el-form-item label="时间维度" prop="dateRange">
                        <el-button-group :autofocus="true">
                         <el-button size="mini" v-for="(item, index) in timeDimensionList" :key="item + index"
                              :disabled="queryParams.type=='2'||queryParams.type=='3'" :class="[item.value === queryParams.dataType ? 'active' : '']"
                              @click="_changeParams('dataType', item.value)">
                              {{ item.name }}
                          </el-button>
                        </el-button-group>
                        <el-date-picker
                        v-model="queryParams.dateRange"
                        style="margin-left:20px;"
                        value-format="yyyy-MM-dd HH"
                        type="datetimerange"
                        range-separator="-"
                        start-placeholder="开始日期"
                        end-placeholder="结束日期"
                        :picker-options="pickerOptions"
                        :default-value="[new Date(), new Date()]"
                        :default-time="['00:00:00']"
                        ></el-date-picker>
                        <el-checkbox v-if="queryParams.dataType !== '1'" v-model="enableComparison" style="margin-left:20px;" @change="handleComparisonChange">启用同比</el-checkbox>
                        <el-date-picker
                        v-if="queryParams.dataType !== '1' && enableComparison"
                        v-model="comparisonDate"
                        style="margin-left:10px;"
                        value-format="yyyy-MM-dd"
                        type="date"
                        placeholder="对比日期"
                        :picker-options="pickerOptions"
                        ></el-date-picker>
                    </el-form-item>
                </el-col>
            </el-query-row>
            <el-row>
                <el-col :span="12">
                    <el-query-row :label="'消耗范围'" :labelWidth="80" class="table-button-group">
                        <el-col :span="11">
                            <el-form-item prop="minCost">
                                <el-input placeholder="请输入消耗" v-model="queryParams.minCost" class="input-with-select">
                                    <el-select v-model="queryParams.minCostOperator" slot="prepend" placeholder="条件"
                                        clearable style="width: 100px;">
                                        <el-option v-for="item in indexSymbol" :key="item.val" :label="item.name"
                                            :value="item.val">
                                        </el-option>
                                    </el-select>
                                </el-input>
                            </el-form-item>
                        </el-col>
                        <el-col class="line" style="width: 15px;">-</el-col>
                        <el-col :span="11">
                            <el-form-item prop="maxCost">
                                <el-input placeholder="请输入消耗" v-model="queryParams.maxCost" class="input-with-select">
                                    <el-select v-model="queryParams.maxCostOperator" slot="prepend" placeholder="条件"
                                        clearable style="width: 100px;">
                                        <el-option v-for="item in indexSymbol" :key="item.val" :label="item.name"
                                            :value="item.val">
                                        </el-option>
                                    </el-select>
                                </el-input>
                            </el-form-item>
                        </el-col>
                    </el-query-row>
                </el-col>
                <el-col :span="12">
                    <el-query-row :label="'roi范围'" :labelWidth="80" class="table-button-group">
                        <el-col :span="11">
                            <el-form-item prop="minRoi">
                                <el-input placeholder="请输入roi" v-model="queryParams.minRoi" class="input-with-select">
                                    <el-select v-model="queryParams.minRoiOperator" slot="prepend" placeholder="条件"
                                        clearable style="width: 100px;">
                                        <el-option v-for="item in indexSymbol" :key="item.val" :label="item.name"
                                            :value="item.val">
                                        </el-option>
                                    </el-select>
                                </el-input>
                            </el-form-item>
                        </el-col>
                        <el-col class="line" style="width: 15px;">-</el-col>
                        <el-col :span="11">
                            <el-form-item prop="maxRoi">
                                <el-input placeholder="请输入roi" v-model="queryParams.maxRoi" class="input-with-select">
                                    <el-select v-model="queryParams.maxRoiOperator" slot="prepend" placeholder="条件"
                                        clearable style="width: 100px;">
                                        <el-option v-for="item in indexSymbol" :key="item.val" :label="item.name"
                                            :value="item.val">
                                        </el-option>
                                    </el-select>
                                </el-input>
                            </el-form-item>
                        </el-col>
                    </el-query-row>
                </el-col>
            </el-row>
            <el-query-row :label="'筛选项'" :labelWidth="80">
                <el-col :span="4" class="mb10">
                    <el-form-item prop="pkg">
                        <el-select v-model="queryParams.pkg" placeholder="应用" style="width: 100%;"
                            collapse-tags filterable clearable @change="_productChange">
                            <el-option v-for="(item, index) in productList" :key="item + index" :label="item.name"
                                :value="item.value" />
                        </el-select>
                    </el-form-item>
                </el-col>
                <el-col :span="4" class="mb10">
                    <el-form-item prop="agentCode">
                        <el-select v-model="queryParams.agentCode" placeholder="代理" style="width: 100%;" @change="_agentChange" filterable clearable>
                            <el-option
                            v-for="item in dict.type.ACCOUNT_AGENT"
                            :key="item.value"
                            :label="item.label"
                            :value="item.value">
                            </el-option>
                        </el-select>
                    </el-form-item>
                </el-col>
                <el-col :span="4" class="mb10">
                    <el-form-item prop="accountId">
                        <el-select v-model="queryParams.accountId" placeholder="账户" style="width: 100%;" :filter-method="accountFilter" filterable clearable @change="_accountChange">
                            <el-option v-for="(item, index) in accountOptions" :key="item.dimensionId" :label="item.dimensionName" :value="item.dimensionId" />
                        </el-select>
                    </el-form-item>
                </el-col>
                <el-col :span="4" class="mb10" v-if="queryParams.type==4||queryParams.type==5||queryParams.type==6">
                    <el-form-item prop="planId">
                      <el-select v-model="queryParams.planId" placeholder="计划" style="width: 100%;" :filter-method="planFilter" filterable clearable @change="_planChange">
                          <el-option v-for="(item, index) in planOptions" :key="item.dimensionId" :label="item.dimensionName" :value="item.dimensionId" />
                      </el-select>
                    </el-form-item>
                </el-col>
                <el-col :span="4" class="mb10" v-if="queryParams.type==5||queryParams.type==6">
                    <el-form-item prop="adgroupId">
                        <el-select v-model="queryParams.adgroupId" placeholder="广告组" style="width: 100%;" :filter-method="adgroupFilter" filterable clearable @change="_adgroupChange">
                            <el-option v-for="(item, index) in adgroupOptions" :key="item.dimensionId" :label="item.dimensionName" :value="item.dimensionId" />
                        </el-select>
                    </el-form-item>
                </el-col>
                <el-col :span="4" class="mb10" v-if="queryParams.type==6">
                    <el-form-item prop="creativeId">
                        <el-select v-model="queryParams.creativeId" placeholder="创意" style="width: 100%;" :filter-method="creativeFilter" filterable clearable>
                            <el-option v-for="item in creativeOptions" :key="item.dimensionId" :label="item.dimensionName" :value="item.dimensionId" />
                        </el-select>
                    </el-form-item>
                </el-col>
                <el-col :span="6" class="mb10">
                    <el-form-item>
                        <el-button type="primary" icon="el-icon-search" @click="handleQuery">搜索</el-button>
                        <el-button icon="el-icon-refresh" @click="resetQuery">重置</el-button>
                        <el-button type="info" v-if="queryParams.dataType==0" :loading="vivoReportTaskLoading" @click="vivoReportTask">拉取报表数据</el-button>
                    </el-form-item>
                </el-col>
            </el-query-row>
        </el-form>

        <el-table v-loading="loading" :data="tableDataList" :key="`table-${queryParams.type}-${queryParams.dataType}`"
            :default-sort="defaultSort" @sort-change="_changeSort" :row-key="getRowKey" stripe>
            <el-table-column type="selection" width="55" align="center" />
            <el-table-column label="日期" align="center" prop="acdate" width="100" sortable="custom">
              <template #default="scope">
                {{scope.row['acdate']}}
              </template>
            </el-table-column>
            <el-table-column label="小时" align="center" width="100" prop="hr" sortable="custom" v-if="queryParams.dataType == '1'">
              <template #default="scope">
                {{scope.row['hr']}}
              </template>
            </el-table-column>
            <el-table-column label="应用" align="center" width="240">
              <template #default="scope">
                  <div>{{ scope.row['appName'] }}</div>
                  <div v-if="queryParams.type !== '3'&&queryParams.type !== '2'">{{ scope.row['accountId'] }}</div>
                  <div v-if="queryParams.type !== '3'&&queryParams.type !== '2'">{{ scope.row['accountName'] }}</div>
                  <div v-if="queryParams.type !== '3'&&queryParams.type !== '2'">{{ scope.row['agentName'] }}</div>
              </template>
            </el-table-column>
            <el-table-column label="账户" align="center" width="240" v-if="queryParams.type == '3'">
              <template #default="scope">
                  <div>{{ scope.row['accountId'] }}</div>
                  <div>{{ scope.row['accountName'] }}</div>
                  <div>{{ scope.row['agentName'] }}</div>
              </template>
            </el-table-column>
            <el-table-column label="计划" align="center" width="240" v-if="queryParams.type == '4' || queryParams.type == '5' || queryParams.type == '6'">
              <template #default="scope">
                  <div>{{ scope.row['planId'] }}</div>
                  <div>{{ scope.row['planName'] }}</div>
                  <div>{{ scope.row['convertTypes'] }}</div>
              </template>
            </el-table-column>
            <el-table-column label="广告组" align="center" width="150" v-if="queryParams.type == '5'">
              <template #default="scope">
                  <div>{{ scope.row['adgroupId'] }}</div>
                  <div>{{ scope.row['adgroupName'] }}</div>
              </template>
            </el-table-column>
            <el-table-column label="创意" align="center" width="150" v-if="queryParams.type == '6'">
              <template #default="scope">
                  <div>{{ scope.row['creativeId'] }}</div>
                  <div>{{ scope.row['creativeName'] }}</div>
              </template>
            </el-table-column>
            <el-table-column label="渠道" align="center" width="100">
              <template #default="scope">
                  <dict-tag :options="dict.type.sys_channel" :value="scope.row['channel']"/>
              </template>
            </el-table-column>
            <el-table-column label="账户数" align="center" width="100" v-if="queryParams.type=='2'">
                <template #default="scope">{{ scope.row['arpuData']['accountCount'] }}</template>
            </el-table-column>
            <el-table-column label="状态" align="center" width="100" prop="status" v-if="queryParams.type !== '2'&&queryParams.type !== '3'"/>
            <el-table-column label="预算" align="center" width="150" v-if="queryParams.type!=='2'&&queryParams.type!=='6'">
                <template #default="scope">
                    <div v-if="scope.row['budget']==-0.01">
                      <div>不限 <el-button v-if="queryParams.type=='3'||queryParams.type=='4'||queryParams.type=='5'" size="mini" type="text" @click="handleDayBudget(scope.row)">修改</el-button></div>
                      <div><el-progress :percentage="+(scope.row.cost / scope.row.cost * 10).toFixed(0)" :format="percentageFormat"/></div>
                    </div>
                    <div v-else>
                      <div>{{ scope.row['budget'] }} <el-button v-if="queryParams.type=='3'||queryParams.type=='4'||queryParams.type=='5'" size="mini" type="text" @click="handleDayBudget(scope.row)">修改</el-button></div>
                      <div><el-progress :percentage="+(scope.row.cost / scope.row.budget * 100).toFixed(0)"/></div>
                    </div>
                    <div v-if="queryParams.type=='3'">余额：{{ scope.row['offer'] }}</div>
                </template>
            </el-table-column>
            <el-table-column label="出价" align="center" v-if="queryParams.type=='5'" width="160">
                <template #default="scope">
                    <div>激活转化成本：{{ scope.row['convertData']['zActivationCost'] }}</div>
                    <div>注册转化成本：{{ scope.row['convertData']['zRegisterCost'] }}</div>
                    <div>付费转化成本：{{ scope.row['convertData']['zPayCost'] }}</div>
                    <div>出价：{{ scope.row['offer'] }} <el-button v-if="queryParams.type=='5'" size="mini" type="text" @click="handleOffer(scope.row)">修改</el-button></div>
                    <div>激活计费比：{{ scope.row['convertData']['zActivationNum']===0? 0:(scope.row['cost']/(scope.row['offer']*scope.row['convertData']['zActivationNum'])).toFixed(2) }}</div>
                    <div>注册计费比：{{ scope.row['convertData']['zRegisterNum']===0? 0:(scope.row['cost']/(scope.row['offer']*scope.row['convertData']['zRegisterNum'])).toFixed(2) }}</div>
                    <div>付费计费比：{{ scope.row['convertData']['zPayNum']===0? 0:(scope.row['cost']/(scope.row['offer']*scope.row['convertData']['zPayNum'])).toFixed(2) }}</div>
                </template>
            </el-table-column>
            <el-table-column label="投产" align="center" prop="cost" width="200" sortable="custom">
                <template #default="scope">
                    <div>
                      账面消耗：{{ scope.row['cost'] }}
                      <span v-if="shouldShowComparison && scope.row.costChangePercent !== null && scope.row.costChangePercent !== undefined" :style="{ color: getComparisonColor(scope.row.costChangePercent) }">
                        {{ formatComparisonDisplay(scope.row.costChangePercent) }}
                      </span>
                    </div>
                    <div>
                      现金消耗：{{ scope.row['cashCost'] }}
                      <span v-if="shouldShowComparison && scope.row.cashCostChangePercent !== null && scope.row.cashCostChangePercent !== undefined" :style="{ color: getComparisonColor(scope.row.cashCostChangePercent) }">
                        {{ formatComparisonDisplay(scope.row.cashCostChangePercent) }}
                      </span>
                    </div>
                    <div>
                      账面ROI：{{ scope.row['roi'] }}
                      <span v-if="shouldShowComparison && scope.row.roiChangePercent !== null && scope.row.roiChangePercent !== undefined" :style="{ color: getComparisonColor(scope.row.roiChangePercent) }">
                        {{ formatComparisonDisplay(scope.row.roiChangePercent) }}
                      </span>
                    </div>
                    <div>真实ROI：{{ scope.row['realRoi'] }}</div>
                    <div >
                      首日回收：{{ scope.row['arpuData']['firstIncome'] }}
                      <span v-if="shouldShowComparison && scope.row.firstIncomeChangePercent !== null && scope.row.firstIncomeChangePercent !== undefined" :style="{ color: getComparisonColor(scope.row.firstIncomeChangePercent) }">
                        {{ formatComparisonDisplay(scope.row.firstIncomeChangePercent) }}
                      </span>
                    </div>
                    <div >
                      首日ROI：{{ (scope.row['arpuData']['firstIncome']/scope.row['cost']).toFixed(2)  }}
                      <span v-if="shouldShowComparison && scope.row.firstIncomeRoiChangePercent !== null && scope.row.firstIncomeRoiChangePercent !== undefined" :style="{ color: getComparisonColor(scope.row.firstIncomeRoiChangePercent) }">
                        {{ formatComparisonDisplay(scope.row.firstIncomeRoiChangePercent) }}
                      </span>
                    </div>
                    <div>
                      归因回收：{{ scope.row['income'] }}
                      <span v-if="shouldShowComparison && scope.row.incomeChangePercent !== null && scope.row.incomeChangePercent !== undefined" :style="{ color: getComparisonColor(scope.row.incomeChangePercent) }">
                        {{ formatComparisonDisplay(scope.row.incomeChangePercent) }}
                      </span>
                    </div>
                    <div v-if="queryParams.type=='2'">总回收：{{ scope.row['totalIncome'] }}</div>
                    <div v-if="queryParams.type=='2'">总roi：{{ scope.row['totalRoi'] }}</div>
                    <div v-if="queryParams.type=='2'">利润：{{ (scope.row['totalIncome']-scope.row['cashCost']).toFixed(2) }}</div>
                    <div v-else>利润：{{ (scope.row['income']-scope.row['cashCost']).toFixed(2) }}</div>
                </template>
            </el-table-column>
            <el-table-column label="arpu分布" align="center" prop="arpuData" width="200" v-if="queryParams.type!=='2'">
                <template #default="scope">
                    <div v-if="scope.row.arpuData && scope.row.arpuData.avg">
                      <div v-if="Array.isArray(scope.row.arpuData.rangeData)" v-for="(item, index) in scope.row.arpuData.rangeData" :key="index">
                        {{ item.incomeRange }}：{{ item.userCount }} ({{ item.incomeRangeRate }}%)
                      </div>
                      <div>
                        平均：{{ scope.row.arpuData.avg }}
                        <span v-if="shouldShowComparison && scope.row.avgArpuChangePercent !== null && scope.row.avgArpuChangePercent !== undefined" :style="{ color: getComparisonColor(scope.row.avgArpuChangePercent) }">
                          {{ formatComparisonDisplay(scope.row.avgArpuChangePercent) }}
                        </span>
                      </div>
                    </div>
                    <div v-else>无</div>
                </template>
            </el-table-column>
            <el-table-column label="ecpm分布" align="center" prop="ecpmData" width="200" v-if="queryParams.type!=='2'">
                <template #default="scope">
                    <div v-if="scope.row.ecpmData && scope.row.ecpmData.ecpmAvg">
                      <div v-if="Array.isArray(scope.row.ecpmData.rangeData)" v-for="(item, index) in scope.row.ecpmData.rangeData" :key="index">
                        {{ item.incomeRange }}：{{ item.userCount }} ({{ item.incomeRangeRate }}%)
                      </div>
                      <div>平均：{{ scope.row.ecpmData.ecpmAvg }}</div>
                    </div>
                    <div v-else>无</div>
                </template>
            </el-table-column>
            <el-table-column label="转化数据" align="center" prop="convertData" width="300" v-if="queryParams.type!=='2'">
                <template #default="scope">
                    <div>展示：{{scope.row['convertData']['impressionNum']}}  cpm：{{ scope.row['convertData']['cpm'] }}</div>
                    <div>点击：{{scope.row['convertData']['clickNum']}}  ({{(scope.row['convertData']['clickRate']*100).toFixed(2)}}%)  成本：{{ scope.row['convertData']['clickCost'] }}</div>
                    <div>下载：{{scope.row['convertData']['downloadNum']}}  ({{(scope.row['convertData']['downloadRate']*100).toFixed(2)}}%)  成本：{{ scope.row['convertData']['downloadCost'] }}</div>
                    <div>启动：{{scope.row['convertData']['startNum']}} ({{(scope.row['convertData']['startRate']*100).toFixed(2)}}%)  成本：{{ scope.row['convertData']['startCost'] }}</div>
                    <div>广告渗透：{{scope.row['convertData']['showNum']}}  ({{(scope.row['convertData']['showRate']*100).toFixed(2)}}%)  成本：{{ scope.row['convertData']['showCost'] }}</div>
                    <div>激活(j)：{{scope.row['convertData']['activationNum']}}  ({{(scope.row['convertData']['activationRate']*100).toFixed(2)}}%)  成本：{{ scope.row['convertData']['activationCost'] }}</div>
                    <div>激活(z)：{{scope.row['convertData']['zActivationNum']}}  ({{(scope.row['convertData']['zActivationRate']*100).toFixed(2)}}%)  成本：{{ scope.row['convertData']['zActivationCost'] }}</div>
                    <div>注册(j)：{{scope.row['convertData']['registerNum']}}  ({{(scope.row['convertData']['registerRate']*100).toFixed(2)}}%)  成本：{{ scope.row['convertData']['registerCost'] }}</div>
                    <div>注册(z)：{{scope.row['convertData']['zRegisterNum']}}  ({{(scope.row['convertData']['zRegisterRate']*100).toFixed(2)}}%)  成本：{{ scope.row['convertData']['zRegisterCost'] }}</div>
                    <div>付费(j)：{{scope.row['convertData']['payNum']}}  ({{(scope.row['convertData']['payRate']*100).toFixed(2)}}%)  成本：{{ scope.row['convertData']['payCost'] }}</div>
                    <div>付费(z)：{{scope.row['convertData']['zPayNum']}}  ({{(scope.row['convertData']['zPayRate']*100).toFixed(2)}}%)  成本：{{ scope.row['convertData']['zPayCost'] }}</div>
                </template>
            </el-table-column>
            <el-table-column label="用户行为" align="center" prop="behaviorData" width="200">
                <template #default="scope">
                    <div>广告总展示：{{ scope.row['behaviorData']['sumIpu'] }}</div>
                    <div>
                      IPU：{{ scope.row['behaviorData']['totalIpu'] }}
                      <span v-if="shouldShowComparison && scope.row.ipuChangePercent !== null && scope.row.ipuChangePercent !== undefined" :style="{ color: getComparisonColor(scope.row.ipuChangePercent) }">
                        {{ formatComparisonDisplay(scope.row.ipuChangePercent) }}
                      </span>
                    </div>
                    <div>IPU(除信息流)：{{ scope.row['behaviorData']['ipu'] }}</div>
                    <div>平均启动：{{ scope.row['behaviorData']['startIpuAvgCount'] }}</div>
                    <div>次留：{{ scope.row['behaviorData']['morrowKeepRate'] }}</div>
                </template>
            </el-table-column>
            <el-table-column label="更新时间" align="center" prop="updatetime" width="100" />
            <el-table-column label="操作" align="center" width="150">
                <template slot-scope="scope">
                  <el-button size="mini" type="text" v-if="queryParams.type=='2'" @click="_queryParams('3',scope.row)">查询账户</el-button>
                  <el-button size="mini" type="text" v-if="queryParams.type=='2' || queryParams.type=='3'" @click="_queryParams('4',scope.row)">查询计划</el-button>
                  <el-button size="mini" type="text" v-if="queryParams.type=='2' || queryParams.type=='3' || queryParams.type=='4'" @click="_queryParams('5',scope.row)">查询广告组</el-button>
                  <el-button size="mini" type="text" v-if="queryParams.type=='2' || queryParams.type=='3' || queryParams.type=='4' || queryParams.type=='5'" @click="_queryParams('6',scope.row)">查询创意</el-button>
                  <el-button size="mini" type="text" v-if="queryParams.type=='5'" @click="handlePassBackList(scope.row)">回传补偿</el-button>
                  <el-button size="mini" type="text" @click="handleViewDataDetails(scope.row)">查看数据详情</el-button>
                </template>
            </el-table-column>
        </el-table>
        <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
            @pagination="getList" />

        <!-- 修改出价弹框 -->
        <el-dialog :title="'修改出价'" :visible.sync="offerOpen" width="500px" append-to-body>
            <el-form ref="offerForm" :model="offerForm" size="small" label-width="120px" class="dialog-form">
                <el-form-item label="出价" prop="offer">
                  <el-input-number v-model="offerForm.offer" :step="0.01" :precision="2" controls-position="right" label="出价"/>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button type="primary" @click="offerSubmitForm">确 定</el-button>
                <el-button @click="offerCancel">取 消</el-button>
            </div>
        </el-dialog>

        <!-- 修改计划日预算弹框 -->
        <el-dialog :title="'修改日预算'" :visible.sync="dayBudgetOpen" width="500px" append-to-body>
            <el-form ref="dayBudgetForm" :model="dayBudgetForm" size="small" label-width="120px" class="dialog-form">
                <el-form-item label="日预算" prop="dayLimit">
                  <el-radio-group v-model="dayBudgetForm.dayLimit">
                    <el-radio-button label="0">不限</el-radio-button>
                    <el-radio-button label="1">预算设置</el-radio-button>
                  </el-radio-group>
                </el-form-item>
                <el-form-item v-if="dayBudgetForm.dayLimit=='1'" label="日预算值" prop="dayBudget">
                  <el-input-number v-model="dayBudgetForm.dayBudget" :step="1" controls-position="right" label="出价"/>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button type="primary" @click="dayBudgetSubmitForm">确 定</el-button>
                <el-button @click="dayBudgetCancel">取 消</el-button>
            </div>
        </el-dialog>

        <!-- 添加或修改参数配置对话框 -->
        <el-dialog :title="'回传补偿列表'" :visible.sync="open" width="1200" append-to-body>
          <el-form :model="passBackQueryParams" size="mini">
            <el-row>
              <el-col :span="16">
                  <el-query-row :label="'arpu范围'" :labelWidth="80" class="table-button-group">
                      <el-col :span="8">
                          <el-form-item prop="minArpu">
                              <el-input placeholder="最小arpu值" v-model="passBackQueryParams.minArpu" clearable/>
                          </el-form-item>
                      </el-col>
                      <el-col class="line" style="width: 15px;">-</el-col>
                      <el-col :span="8">
                          <el-form-item prop="maxArpu">
                              <el-input placeholder="最大arpu值" v-model="passBackQueryParams.maxArpu" clearable/>
                          </el-form-item>
                      </el-col>
                  </el-query-row>
              </el-col>
              <el-col :span="16">
                  <el-query-row :label="'ecpm范围'" :labelWidth="80" class="table-button-group">
                      <el-col :span="8">
                          <el-form-item prop="minEcpm">
                              <el-input placeholder="最小ecpm值" v-model="passBackQueryParams.minEcpm" clearable/>
                          </el-form-item>
                      </el-col>
                      <el-col class="line" style="width: 15px;">-</el-col>
                      <el-col :span="8">
                          <el-form-item prop="maxEcpm">
                              <el-input placeholder="最大ecpm值" v-model="passBackQueryParams.maxEcpm" clearable/>
                          </el-form-item>
                      </el-col>
                  </el-query-row>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="16">
                  <el-query-row :label="'ipu范围'" :labelWidth="80" class="table-button-group">
                      <el-col :span="8">
                          <el-form-item prop="minIpu">
                              <el-input placeholder="最小ipu值" v-model="passBackQueryParams.minIpu" clearable/>
                          </el-form-item>
                      </el-col>
                      <el-col class="line" style="width: 15px;">-</el-col>
                      <el-col :span="8">
                          <el-form-item prop="maxIpu">
                              <el-input placeholder="最大ipu值" v-model="passBackQueryParams.maxIpu" clearable/>
                          </el-form-item>
                      </el-col>
                  </el-query-row>
              </el-col>
              <el-col :span="16">
                  <el-query-row :label="'回传类型'" :labelWidth="80" class="table-button-group">
                      <el-col :span="16">
                          <el-form-item>
                              <el-checkbox v-model="passBackQueryParams.activation">激活</el-checkbox>
                              <el-checkbox v-model="passBackQueryParams.register">注册</el-checkbox>
                              <el-checkbox v-model="passBackQueryParams.pay">付费</el-checkbox>
                          </el-form-item>
                      </el-col>
                  </el-query-row>
              </el-col>
              <el-col :span="13">
                <el-form-item :label="'时间范围'" prop="passBackDateRange">
                  <el-date-picker
                  v-model="passBackQueryParams.passBackDateRange"
                  value-format="yyyy-MM-dd"
                  type="datetimerange"
                  range-separator="-"
                  start-placeholder="开始日期"
                  end-placeholder="结束日期"
                  :picker-options="pickerOptions"
                  :default-value="[new Date(), new Date()]"
                  :default-time="['00:00:00']"/>
                </el-form-item>
              </el-col>
              <el-col :span="2" class="mb10">
                  <el-form-item>
                      <el-button type="primary" icon="el-icon-search" @click="queryPassBackList">搜索</el-button>
                  </el-form-item>
              </el-col>
              <el-col :span="2" class="mb10">
                  <el-form-item>
                      <el-button icon="el-icon-refresh" size="mini" @click="reset">重置</el-button>
                  </el-form-item>
              </el-col>
            </el-row>
          </el-form>
          <el-table v-loading="passBackLoading" :data="passBackDataList" :height="300" @selection-change="handleSelectionChange">
              <el-table-column type="selection" width="55" align="center" />
              <el-table-column label="监测日期" align="center" width="100" prop="date"/>
              <el-table-column label="监测小时" align="center" width="100" prop="achour"/>
              <el-table-column label="oaId" align="center" width="300" prop="oaId"/>
              <el-table-column label="arpu" align="center" width="100" prop="arpu"/>
              <el-table-column label="ecpm" align="center" width="100" prop="ecpm"/>
              <el-table-column label="ipu" align="center" width="100" prop="ipu"/>
              <el-table-column label="已回传" align="center" width="100">
                 <template slot-scope="scope">
                   <div v-if="scope.row.activation">激活</div>
                   <div v-if="scope.row.register">注册</div>
                   <div v-if="scope.row.pay">付费</div>
                 </template>
              </el-table-column>
          </el-table>
          <pagination v-show="passBackTotal > 0" :total="passBackTotal" :page.sync="passBackQueryParams.pageNum" :limit.sync="passBackQueryParams.pageSize"
              @pagination="queryPassBackList" />
          <div slot="footer" class="dialog-footer">
            <el-row>
              <el-col :span="17">
                <el-checkbox-group v-model="checkEvent">
                  <el-checkbox v-for="event in eventList" :label="event.value" :key="event.value">{{event.name}}</el-checkbox>
                </el-checkbox-group>
              </el-col>
              <el-col :span="6">
                <el-button type="primary" @click="submitForm">确定回传</el-button>
                <el-button @click="cancel">取 消</el-button>
              </el-col>
            </el-row>
          </div>
        </el-dialog>
    </div>
</template>

<script>
import baseTableAdv from '@/mixins/baseTableAdv';
import { computedDate, arrParamToStr, formatTime } from '@/utils/index';
import { getAccountList } from "@/api/place-manage/account";
import { passBackList, batchCompensate } from "@/api/common/compensate";
import { getPlaceList ,listTable ,updatePrice ,updatePlanDayBudget ,vivoTask } from "@/api/place-report/vivoSearch";
export default {
    name: 'Search',
    mixins: [baseTableAdv],
    dicts: ['sys_channel','ACCOUNT_AGENT'],
    data() {
        return {
            // 默认排序
            defaultSort: { prop: 'cost', order: 'descending' },
            eventList:[{name:'激活',value:1},{name:'注册',value:3},{name:'付费',value:4}],
            // 是否显示弹出层
            open: false,
            passBackLoading: false,
            passBackDataList:[],
            passBackTotal: 0,
            checkEvent: [],
            vivoReportTaskLoading: false,
            // 账户
            accountList: [],
            accountOptions: [],
            offerOpen:false,
            offerForm:{
              accountId:'',
              adgroupId:'',
              acdate:0,
              type:'0',
              offer:0
            },
            dayBudgetOpen:false,
            dayBudgetForm:{
              accountId:'',
              planId:'',
              acdate:0,
              type:'0',
              dayLimit: 0,
              dayBudget:0
            },
            // 计划
            planList: [],
            planOptions: [],
            adgroupList: [],
            adgroupOptions: [],
            creativeList: [],
            creativeOptions: [],
            passBackQueryParams: {
                pageNum: 1,
                pageSize: 10,
                beginDate: '',
                endDate: '',
                minArpu: '',
                maxArpu: '',
                minEcpm: '',
                maxEcpm: '',
                minIpu: '',
                maxIpu: '',
                channel: '',
                pkg: '',
                planId: '',
                activation: false,
                register: false,
                pay: false
            },
            pickerOptions: {
              shortcuts: [{
                text: '今天',
                onClick(picker) {
                  const start = new Date();
                  start.setHours(0, 0, 0, 0);
                  const end = new Date();
                  end.setHours(23, 59, 59, 999);
                  picker.$emit('pick', [start, end]);
                }
              },{
                text: '昨天',
                onClick(picker) {
                  const end = new Date();
                  const start = new Date();
                  start.setTime(start.getTime() - 3600 * 1000 * 24);
                  start.setHours(0, 0, 0, 0);
                  end.setTime(end.getTime() - 3600 * 1000 * 24);
                  end.setHours(23, 59, 59, 999);
                  picker.$emit('pick', [start, end]);
                }
              },{
                text: '上周',
                onClick(picker) {
                  const end = new Date();
                  const start = new Date();
                  // 计算上周的周一（自然周以周一开始）
                  start.setDate(start.getDate() - start.getDay() - 6);
                  start.setHours(0, 0, 0, 0);
                  // 计算上周的周日
                  end.setDate(start.getDate() + 6);
                  end.setHours(23, 59, 59, 999);
                  picker.$emit('pick', [start, end]);
                }
              }, {
                text: '本月',
                onClick(picker) {
                  const now = new Date();
                  const year = now.getFullYear();
                  const month = now.getMonth(); // 0-11
                  const start = new Date(year, month , 1);
                  start.setHours(0, 0, 0, 0);
                  const end = new Date(year, month+1, 0);
                  end.setHours(23, 59, 59, 999);
                  picker.$emit('pick', [start, end]);
                }
              }, {
                text: '上月',
                onClick(picker) {
                  const now = new Date();
                  const year = now.getFullYear();
                  const month = now.getMonth(); // 0-11
                  const start = new Date(year, month - 1, 1);
                  start.setHours(0, 0, 0, 0);
                  const end = new Date(year, month, 0);
                  end.setHours(23, 59, 59, 999);
                  picker.$emit('pick', [start, end]);
                }
              }]
            },
            // 表格数据
            tableDataList: [],
            tableData: {},
            // 同比功能相关
            enableComparison: true,
            comparisonDate: '',
            queryParams: {
                pageNum: 1,
                pageSize: 10,
                type: '3', // 数据维度
                dataType: '0', //时间维度
                dateRange: [computedDate(new Date()), computedDate(new Date())],
                minCost: '',
                minCostOperator: '',
                maxCost: '',
                maxCostOperator: '',
                minRoi: '',
                minRoiOperator: '',
                maxRoi: '',
                maxRoiOperator: '',
                pkg: '',
                channel: '',
                accountName: '',
                accountId: '',
                agentCode: '',
                scheme: '',
            },
            // 数据维度
            dataDimensionList: [
              // { name: '渠道', value: '1' },
              { name: '应用', value: '2' },
              { name: '账户', value: '3' },
              { name: '计划', value: '4' },
              { name: '广告组', value: '5' },
              { name: '创意', value: '6' }],
            // 时间维度
            timeDimensionList: [{name: '天', value: '0'}, {name: '小时', value: '1'}],
            // Symbol
            indexSymbol: [{ name: "大于等于", val: "1" }, { name: "小于等于", val: "2" }, { name: "等于", val: "3" }, { name: "大于", val: "4" }, { name: "小于", val: "5" }],
            currRowIndex: null
        }
    },
    created() {
      if (this.$route.query && this.$route.query.type) this.queryParams.type = this.$route.query.type;
      if (this.$route.query && this.$route.query.pkg) this.queryParams.pkg = this.$route.query.pkg;
      if (this.$route.query && this.$route.query.accountId) this.queryParams.accountId = this.$route.query.accountId;
      if (this.$route.query && this.$route.query.planId) this.queryParams.planId = this.$route.query.planId;
      if (this.$route.query && this.$route.query.adgroupId) this.queryParams.adgroupId = this.$route.query.adgroupId;
      if (this.$route.query && this.$route.query.dataType) this.queryParams.dataType = this.$route.query.dataType;

      this._getProductList();
      this._getPlaceList(3);
      this._getPlaceList(4);
      this._getPlaceList(5);
      this._getPlaceList(6);
      this._integrationParams();
      this.getList();
    },
    mounted() {
        // if (this.$route.query && this.$route.query.pkg) this.queryParams.pkg = this.$route.query.pkg;
    },
    computed: {
      // 判断是否应该显示同比功能（小时维度下不显示）
      shouldShowComparison() {
        return this.queryParams.dataType !== '1' && this.enableComparison;
      }
    },

    methods: {
      _changeParams(key, value) {
        let vm = this
        vm.queryParams[key] = value
        if(vm.queryParams["type"]==='2'||vm.queryParams["type"]==='3'){
          vm.queryParams.dataType = '0'
        }
        // 处理时间维度切换时的同比功能
        if (key === 'dataType') {
          vm.handleDataTypeChange(value);
        }
        // 清空当前数据，避免渲染错误
        vm.tableDataList = [];
        // 强制表格重新渲染，解决列错位问题
        vm.$nextTick(() => {
          vm.handleQuery();
        });
      },
      // 处理时间维度切换
      handleDataTypeChange(newDataType) {
        if (newDataType === '1') {
          // 切换到小时维度：禁用同比功能
          this.enableComparison = false;
        } else {
          // 切换到天维度：恢复同比功能
          this.enableComparison = true;
          // 如果对比日期未设置，初始化为昨天
          if (!this.comparisonDate) {
            this.comparisonDate = computedDate(new Date(), -1);
          }
        }
      },
      // 处理同比功能开关
      handleComparisonChange() {
        // 重新查询数据
        this.handleQuery();
      },
      // 获取行的唯一标识，用于表格重新渲染时保持数据一致性
      getRowKey(row) {
        // 小时维度需要包含 hr 字段
        const hrPart = this.queryParams.dataType === '1' ? `-${row.hr || 0}` : '';

        if (this.queryParams.type === '2') {
          return `${row.acdate}${hrPart}-${row.pkg}-${row.channel}`;
        } else if (this.queryParams.type === '3') {
          return `${row.acdate}${hrPart}-${row.accountId}-${row.channel}`;
        } else if (this.queryParams.type === '4') {
          return `${row.acdate}${hrPart}-${row.planId}-${row.channel}`;
        } else if (this.queryParams.type === '5') {
          return `${row.acdate}${hrPart}-${row.adgroupId}-${row.channel}`;
        } else if (this.queryParams.type === '6') {
          return `${row.acdate}${hrPart}-${row.creativeId}-${row.channel}`;
        }
        return `${row.acdate}${hrPart}-${row.pkg || row.accountId || row.planId || row.adgroupId || row.creativeId}-${row.channel}`;
      },

      // 格式化同比显示
      formatComparisonDisplay(percentage) {
        if (percentage === null || percentage === undefined) return '';
        const sign = percentage >= 0 ? '+' : '';
        return `${sign}${percentage}%`;
      },
      // 获取同比显示的颜色
      getComparisonColor(percentage) {
        if (percentage === null || percentage === undefined) return '';
        return percentage >= 0 ? '#67C23A' : '#F56C6C';
      },
      vivoReportTask(){
        this.vivoReportTaskLoading = true;
        let acDate = this.queryParams.dateRange[0];
        acDate = acDate.replaceAll('-','').replaceAll(' ','').substring(0,8);
        let param = {'startDate':acDate,'endDate': acDate};
        vivoTask(arrParamToStr({ ...param })).then(response => {
          if(response.code==200){
            this.getList();
            this.$modal.msgSuccess("执行成功");
          }else{
            this.$modal.msgError("执行失败");
          }
        }).finally(() => {
          this.vivoReportTaskLoading = false;
        });
      },
      handleOffer(row){
        let vm = this;
        vm.offerOpen = true;
        vm.offerForm.accountId = row.accountId;
        vm.offerForm.adgroupId = row.adgroupId;
        vm.offerForm.acdate = row.acdate;
        vm.offerForm.type = row.type;
        vm.offerForm.offer = row.offer;
      },
      offerSubmitForm (){
        let vm = this;
        vm.offerOpen = false;
        updatePrice(vm.offerForm).then(response => {
          if(response.code==200){
            vm.offerForm = {accountId:'',adgroupId:'',acdate:0,type:'0',offer:0};
            this.getList();
            this.$modal.msgSuccess("修改成功");
          }else{
            this.$modal.msgError("修改失败");
          }
        })
      },
      offerCancel(){
        let vm = this;
        vm.offerOpen = false;
        vm.offerForm = {accountId:'',adgroupId:'',acdate:0,type:'0',offer:0};
      },
      handleDayBudget(row){
        let vm = this;
        vm.dayBudgetOpen = true;
        vm.dayBudgetForm.accountId = row.accountId;
        vm.dayBudgetForm.planId = row.planId;
        vm.dayBudgetForm.adgroupId = row.adgroupId;
        vm.dayBudgetForm.acdate = row.acdate;
        vm.dayBudgetForm.type = row.type;
        if(row.budget<0){
          vm.dayBudgetForm.dayLimit = '0'
        }else{
          vm.dayBudgetForm.dayLimit = '1'
          vm.dayBudgetForm.dayBudget = row.budget;
        }
      },
      dayBudgetSubmitForm (){
        let vm = this;
        vm.dayBudgetOpen = false;
        updatePlanDayBudget(vm.dayBudgetForm).then(response => {
          if(response.code==200){
            vm.dayBudgetForm = {accountId:'',planId:'',acdate:0,type:'0',dayLimit:0,dayBudget:0};
            this.getList();
            this.$modal.msgSuccess("修改成功");
          }else{
            this.$modal.msgError("修改失败");
          }
        })
      },
      dayBudgetCancel(){
        let vm = this;
        vm.dayBudgetOpen = false;
        vm.dayBudgetForm = {accountId:'',planId:'',acdate:0,type:'0',dayLimit:0,dayBudget:0};
      },
      percentageFormat (row){
          return '♾️';
      },
        _getPlaceList(type, params = {}) {
          const requestParams = { type: type, ...params };
          getPlaceList(requestParams).then(response => {
            if(type == 3){
              this.accountList = response.data
              this.accountOptions = response.data
            }else if(type == 4){
              this.planList = response.data;
              this.planOptions = response.data;
            }else if(type == 5){
              this.adgroupList = response.data;
              this.adgroupOptions = response.data;
            }else if(type == 6){
              this.creativeList = response.data;
              this.creativeOptions = response.data;
            }
          })
        },
        accountFilter(query) {
          if (!query) {
            this.accountOptions = this.accountList;
            return;
          }
          const keyword = query.toLowerCase();
          this.accountOptions = this.accountList.filter(item =>
            item.accountId.toLowerCase().includes(keyword) ||
            item.accountName.toLowerCase().includes(keyword)
          );
        },
        planFilter(query) {
          if (!query) {
            this.planOptions = this.planList;
            return;
          }
          const keyword = query.toLowerCase();
          this.planOptions = this.planList.filter(item =>
            item.dimensionId.toLowerCase().includes(keyword) ||
            item.dimensionName.toLowerCase().includes(keyword)
          );
        },
        adgroupFilter(query) {
          if (!query) {
            this.adgroupOptions = this.adgroupList;
            return;
          }
          const keyword = query.toLowerCase();
          this.adgroupOptions = this.adgroupList.filter(item =>
            item.dimensionId.toLowerCase().includes(keyword) ||
            item.dimensionName.toLowerCase().includes(keyword)
          );
        },
        creativeFilter(query) {
          if (!query) {
            this.creativeOptions = this.creativeList;
            return;
          }
          const keyword = query.toLowerCase();
          this.creativeOptions = this.creativeList.filter(item =>
            item.dimensionId.toLowerCase().includes(keyword) ||
            item.dimensionName.toLowerCase().includes(keyword)
          );
        },
        // 应用变化处理
        _productChange(value) {
          let vm = this;

          // 清空下级选择
          vm.queryParams.accountId = '';
          vm.queryParams.planId = '';
          vm.queryParams.adgroupId = '';

          // 重新获取下级数据
          if (value) {
            vm._getPlaceList(3, { pkg: value }); // 获取账户列表
            vm._getPlaceList(4, { pkg: value }); // 获取计划列表
            vm._getPlaceList(5, { pkg: value }); // 获取广告组列表
            vm._getPlaceList(6, { pkg: value }); // 获取创意列表
          }
        },
        // 账户变化处理
        _accountChange(value) {
          let vm = this;

          // 清空下级选择
          vm.queryParams.planId = '';
          vm.queryParams.adgroupId = '';

          // 重新获取下级数据
          if (value && vm.queryParams.pkg) {
            const params = { pkg: vm.queryParams.pkg, accountId: value };
            vm._getPlaceList(4, params); // 获取计划列表
            vm._getPlaceList(5, params); // 获取广告组列表
            vm._getPlaceList(6, params); // 获取创意列表
          }
        },
        // 计划变化处理
        _planChange(value) {
          let vm = this;

          // 清空下级选择
          vm.queryParams.adgroupId = '';

          // 重新获取下级数据
          if (value && vm.queryParams.pkg) {
            const params = {
              pkg: vm.queryParams.pkg,
              planId: value
            };
            if (vm.queryParams.accountId) {
              params.accountId = vm.queryParams.accountId;
            }
            vm._getPlaceList(5, params); // 获取广告组列表
            vm._getPlaceList(6, params); // 获取创意列表
          }
        },
        // 广告组变化处理
        _adgroupChange(value) {
          let vm = this;

          // 重新获取下级数据（创意）
          if (value && vm.queryParams.pkg) {
            const params = {
              pkg: vm.queryParams.pkg,
              adgroupId: value
            };
            if (vm.queryParams.accountId) {
              params.accountId = vm.queryParams.accountId;
            }
            if (vm.queryParams.planId) {
              params.planId = vm.queryParams.planId;
            }
            vm._getPlaceList(6, params); // 获取创意列表
          }
        },
        _queryParams(type,row) {
          let vm = this
          if(type=='4' || type=='5'){
            const newQueryParams = {...vm.queryParams};
            newQueryParams.type = type;
            newQueryParams.pkg = row.pkg;
            if(row.accountId){
              newQueryParams.accountId = row.accountId;
            }
            if(row.planId!=0){
              newQueryParams.planId = row.planId;
            }
            const queryString = new URLSearchParams(newQueryParams).toString();
            const url = `https://tools.hnyynet.com.cn/prom-admin-html/#/place-report/vivoSearch?${queryString}`;
            // const url = `http://localhost:1024/prom-admin-html/#/place-report/vivoSearch?${queryString}`;
            window.open(url, '_blank');
          }else{
            vm.queryParams.type = type
            vm.queryParams.pkg = row.pkg
            vm.queryParams.accountId = row.accountId;
            if(row.planId!=0){
              vm.queryParams.planId = row.planId;
            }
            if(row.adgroupId!=0){
              vm.queryParams.adgroupId = row.adgroupId;
            }
            vm.handleQuery()
          }
        },
        // 状态修改
        _changeStatus (row) {
            let vm = this;
            this.$modal.confirm(`是否确认修改该状态？`).then(() => {
                return updateStatus({status: row.status});
            }).then(response => {
                if (response.code === 200) {
                    vm.handleQuery();
                    vm.$modal.msgSuccess("操作成功！");
                } else {
                    vm.$modal.msgError("操作失败！");
                }
            }).catch(() => {});
        },
        /** 查询ROI数据列表 */
        getList() {
            let vm = this;
            vm.loading = true;
            // 确保日期参数正确转换
            vm._integrationParams();
            // 如果启用同比且有对比日期，传递给后端
            if(vm.enableComparison) {
              // 如果对比日期未设置，初始化为昨天
              if (!vm.comparisonDate) {
                vm.comparisonDate = computedDate(new Date(), -1);
              }
              vm.queryParams.comparisonDate = vm.comparisonDate.replace(/-/g, '').replace(/\s+/g,"");
            } else {
              // 未启用同比时，清空 comparisonDate 参数
              vm.queryParams.comparisonDate = '';
            }
            listTable(arrParamToStr({ ...vm.queryParams })).then(response => {
                vm.tableDataList = response.rows.map(item => {
                    item.status = item.status;
                    item.updatetime = formatTime(item.updatetime);
                    // item.updatetime = item.updatetime;
                    if(item.arpuData) item.arpuData = JSON.parse(item.arpuData);
                    if(item.ecpmData) item.ecpmData = JSON.parse(item.ecpmData);
                    if(item.convertData) item.convertData = JSON.parse(item.convertData);
                    if(item.behaviorData) item.behaviorData = JSON.parse(item.behaviorData);
                    if(item.uploadData) item.uploadData = JSON.parse(item.uploadData);
                    return item;
                });
                vm.tableData = response.totalData;
                vm.total = response.total;
                vm.loading = false;
            }).catch(error => {
                vm.loading = false;
                console.log(error);
            });
        },
        handlePassBackList(row){
          let vm = this;
          vm.open = true;
          vm.passBackQueryParams.channel = row.channel;
          vm.passBackQueryParams.pkg = row.pkg;
          vm.passBackQueryParams.planId = row.planId;
          vm.passBackQueryParams.beginDate = this.offsetDay(row.acdate+'',-6);
          vm.passBackQueryParams.endDate = row.acdate;
          vm.queryPassBackList();
        },
        offsetDay(dateStr,dayNum) {
          const year = parseInt(dateStr.slice(0, 4));
          const month = parseInt(dateStr.slice(4, 6)) - 1;
          const day = parseInt(dateStr.slice(6, 8));
          const date = new Date(year, month, day);
          date.setDate(date.getDate() + dayNum);
          const y = date.getFullYear();
          const m = String(date.getMonth() + 1).padStart(2, '0');
          const d = String(date.getDate()).padStart(2, '0');
          return `${y}${m}${d}`;
        },
        queryPassBackList(){
          let vm = this;
          vm.passBackLoading = true;
          if(vm.passBackQueryParams.passBackDateRange){
            vm.passBackQueryParams.beginDate = vm.passBackQueryParams.passBackDateRange[0]
            vm.passBackQueryParams.endDate = vm.passBackQueryParams.passBackDateRange[1]
          }
          passBackList(arrParamToStr({ ...vm.passBackQueryParams })).then(response => {
                vm.passBackDataList = response.rows;
                vm.passBackTotal = response.total;
                vm.passBackLoading = false;
            }).catch(error => {
                vm.passBackLoading = false;
                console.log(error);
            });
        },
        // 多选框选中数据
        handleSelectionChange(selection) {
          this.oaids = selection.map(item => item.oaId)
          this.single = selection.length!=1
          this.multiple = !selection.length
        },
        submitForm(){
            let vm = this;
            const params = [];
            if (vm.oaids.length > 0 && vm.checkEvent.length > 0) {
              for (const oaid of this.oaids) {
                for (const type of this.checkEvent) {
                    params.push({"oaid":oaid,"type":type,"channel":vm.passBackQueryParams.channel,"pkg":vm.passBackQueryParams.pkg});
                }
              }
            }
            batchCompensate(params).then(response => {
              if(response.code==200){
                this.$modal.msgSuccess("回传成功");
              }else{
                this.$modal.msgSuccess(response.msg);
              }
            }).catch(error => {
                console.log(error);
            });
        },
        // 取消按钮
        cancel() {
          this.open = false;
          reset()
        },
        resetQuery(){
          this.queryParams.pageNum = 1;
          this.queryParams.pageSize = 10;
          this.queryParams.dateRange = [computedDate(new Date()), computedDate(new Date())];
          this.queryParams.minCost = '';
          this.queryParams.minCostOperator = '';
          this.queryParams.maxCost = '';
          this.queryParams.maxCostOperator = '';
          this.queryParams.minRoi = '';
          this.queryParams.minRoiOperator = '';
          this.queryParams.maxRoi = '';
          this.queryParams.maxRoiOperator = '';
          this.queryParams.pkg = '';
          this.queryParams.accountName = '';
          this.queryParams.accountId = '';
          this.queryParams.planId = '';
          this.queryParams.adgroupId = '';
          this.queryParams.creativeId = '';
          this.queryParams.agentCode = '';
          this.accountOptions = this.accountList;
          this.planOptions = this.planList;
          this.adgroupOptions = this.adgroupList;
          this.creativeOptions = this.creativeList;
          // 重置同比功能
          this.enableComparison = true;
          this.comparisonDate = computedDate(new Date(), -1);
          this.comparisonData = [];
          this.comparisonLoading = false;
          this.handleQuery();
        },
        reset(){
          let vm = this;
          vm.passBackQueryParams.passBackDateRange = [computedDate(new Date()), computedDate(new Date())];
          vm.passBackQueryParams.minArpu = '';
          vm.passBackQueryParams.maxArpu = '';
          vm.passBackQueryParams.minEcpm = '';
          vm.passBackQueryParams.maxEcpm = '';
          vm.passBackQueryParams.minIpu = '';
          vm.passBackQueryParams.maxIpu = '';
          vm.passBackQueryParams.activation = false;
          vm.passBackQueryParams.register = false;
          vm.passBackQueryParams.pay = false;
          vm.queryPassBackList()
        },
        // 查看数据详情
        handleViewDataDetails(row) {
          let vm = this;

          // 确保日期参数已经被正确处理
          vm._integrationParams();

          // 构建路由参数
          const routeParams = {
            pkg: row.pkg || vm.queryParams.pkg, // 应用包名
            appName: row.appName, //应用名称
            channel: row.channel, // 渠道编码
            type: vm.queryParams.type, // 维度类型
            dataType: vm.queryParams.dataType, // 时间维度类型 (0:天, 1:小时)
            beginDate: vm.queryParams.beginDate, // 开始日期
            endDate: vm.queryParams.endDate, // 结束日期
          };

          // 根据不同维度传递对应的ID
          if (vm.queryParams.type === '3') {
            // 账户维度
            routeParams.accountId = row.accountId;
            routeParams.accountName = row.accountName;
          } else if (vm.queryParams.type === '4') {
            // 计划维度
            routeParams.accountId = row.accountId;
            routeParams.accountName = row.accountName;
            routeParams.planId = row.planId;
            routeParams.planName = row.planName;
          } else if (vm.queryParams.type === '5') {
            // 广告组维度
            routeParams.accountId = row.accountId;
            routeParams.accountName = row.accountName;
            routeParams.planId = row.planId;
            routeParams.planName = row.planName;
            routeParams.adgroupId = row.adgroupId;
            routeParams.adgroupName = row.adgroupName;
          }

          // 跳转到数据详情页面
          const routeUrl = vm.$router.resolve({
            path: '/place-report/vivoSearch/dataDetails/index',
            query: routeParams
          });
          window.open(routeUrl.href, '_blank');
        }
    }
}
</script>
<style lang="scss" scoped>
  .like {
      cursor: pointer;
      font-size: 25px;
      display: inline-block;
    }
  .top-total {
    margin-bottom: 20px;
    width: 100%;
    display: flex;
    .item {
        margin-right: 20px;
        padding: 20px;
        width: 200px;
        border: #333 1px solid;
        border-radius: 5px;
        color: #333;
        h3 {
            margin: 0 0 10px;
            font-size: 18px;
            font-weight: bold;
        }
        p {
            margin: 0px;
            font-size: 14px;
            font-weight: bold;
        }
    }
  }
</style>
